import { Action, configureStore, getDefaultMiddleware, Middleware } from '@reduxjs/toolkit';

import reduxThunk, { ThunkAction } from 'redux-thunk';
import reduxLogger from 'redux-logger';

import rootReducer, { RootState } from './rootReducer';

const middleware: Middleware[] = [reduxThunk, ...getDefaultMiddleware()];

if (process.env.NODE_ENV !== 'production') {
  middleware.push(reduxLogger);
}

const store = configureStore({
  reducer: rootReducer,
  middleware: middleware,
});

if (process.env.NODE_ENV === 'development' && module.hot) {
  module.hot.accept('./rootReducer', () => {
    const newRootReducer = require('./rootReducer').default;
    store.replaceReducer(newRootReducer);
  });
}

export type AppDispatch = typeof store.dispatch;

export type AppThunk = ThunkAction<void, RootState, null, Action<string>>;

export default store;
